package com.fenghongzhang.day014;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button start;
    private Button stop;
    private Button bind;
    private Button unbind;
    private Intent intent;
    private ServiceConnection serviceConnection;
    private MyService.MyBinder binder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start = (Button) findViewById(R.id.start);
        stop = (Button) findViewById(R.id.stop);

        bind = (Button) findViewById(R.id.bind);
        unbind = (Button) findViewById(R.id.unbind);



        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                //服务连接对象
                 serviceConnection =  new ServiceConnection(){
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                         binder = (MyService.MyBinder) service;
                        binder.callPlay();
                    }
                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                    }
                };
                bindService(intent,serviceConnection,BIND_AUTO_CREATE);
            }
        });

        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(serviceConnection);
            }
        });

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(intent);
            }
        });
    }

    public void next(View view) {
        binder.callNext("哈哈");
    }
}
